package davidlauzon.activerecord.connection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import davidlauzon.activerecord.recordset.RecordSet;
import davidlauzon.activerecord.recordset.SqliteRecordSet;
import davidlauzon.activerecord.visitor.SqliteSerializer;

public class SqliteAdapter extends ConnectionAdapter
{
    static public final String DRIVER = "sqlite";
    
    
    public SqliteAdapter(String dbName) throws ClassNotFoundException, SQLException {
        super(dbName);
        setDriver(DRIVER);
        setSerializer( new SqliteSerializer() );
        Class.forName("org.sqlite.JDBC");
        connect();
    }

    @Override
    public String getUrl() {  return "jdbc:" + DRIVER + ":" + _dbName; }

    @Override
    public long getLastInsertId() throws SQLException
    {
        Statement statement = createStatement();
        ResultSet set       = statement.executeQuery("SELECT last_insert_rowid()");
        long lastInsertId   = set.getLong(1);
        
        set.close();
        statement.close();
        
        return lastInsertId;
    }
    
    @Override
    protected Connection getConnection() throws SQLException {
        if (_connection == null) {
            _connection = DriverManager.getConnection(getUrl());
            log("Connected to database '" + getDbName() + "'");
        }
        return _connection;
    }

    /**
     * SQLite only supports TYPE_FORWARD_ONLY cursors
     * Unfortunatly SQLite does not support scrollable (SCROLL_[IN]SENSITIVE) ResultSet.
     * Therefore it won't be possible to use it as an Iterable
     */
    @Override
    protected Statement createStatement() throws SQLException {
        //return getConnection().createStatement( ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY );
        return getConnection().createStatement(  );
    }
    
    protected RecordSet createRecordSet( Statement statement, ResultSet set ) {
        return new SqliteRecordSet( statement, set );
    }
}
